package io.gitee.mingbaobaba.security.core.repository;

import org.apache.commons.lang3.StringUtils;

import java.text.MessageFormat;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.UUID;

/**
 * <p>验证码默认实现</p>
 *
 * @author yingsheng.ye
 * @version 1.0.0
 * @since 2023/9/21 9:31
 */
public class SecurityCaptchaRepositoryDefaultImpl implements SecurityCaptchaRepository {
    private final Map<String, LocalDateTime> captchaMap = new HashMap<>();

    @Override
    public String saveCaptcha(String code, long expiry) {
        String captchaSeqId = UUID.randomUUID().toString();
        captchaMap.put(MessageFormat.format("{0}-{1}", captchaSeqId, code).toLowerCase(), LocalDateTime.now().plusSeconds(expiry));
        return captchaSeqId;
    }

    @Override
    public Boolean validCaptcha(String captchaSeqId, String code) {
        String validCode = MessageFormat.format("{0}-{1}", captchaSeqId, code).toLowerCase();
        if (StringUtils.isBlank(validCode)) {
            return false;
        }
        LocalDateTime localDateTime = captchaMap.get(validCode);
        if (Objects.isNull(localDateTime)) {
            return false;
        }
        captchaMap.remove(validCode);
        return localDateTime.isAfter(LocalDateTime.now());
    }
}
